<!DOCTYPE html>
<html>

<head>
  <title>open-wa</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.2.0/socket.io.js" 
    integrity="sha512-WL6WGKMPBiM9PnHRYIn5YEtq0Z8XP4fkVb4qy7PP4vhmYQErJ/dySyXuFIMDf1eEYCXCrQrMJfkNwKc9gsjTjA==" 
    crossorigin="anonymous" referrerpolicy="no-referrer"></script>


  <style>
    body {
      color: #1a2c37;
      font-family: 'Helvetica', sans-serif;
      font-size: 86%;
      padding: 2em;
    }

    .info {
      font-size: 120%;
      font-weight: bold;
    }

    .log {
      border: 1px solid #ccc;
      height: 300px;
      padding: 0.5em;
      overflow: hidden;
      position: relative;
      overflow-y: scroll;
      height: 400px;
      min-width: 400px;
      margin: auto;
      margin-left: 16px;
      max-width: 50%;
      width: 50%;
      white-space: pre-wrap;       /* css-3 */
      white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
      white-space: -pre-wrap;      /* Opera 4-6 */
      white-space: -o-pre-wrap;    /* Opera 7 */
      word-wrap: break-word;       /* Internet Explorer 5.5+ */
    }

    .qr {
      width: 400px;
      height: 400px;
      margin: auto;
    }

    .eventwrap {
      display: flex;
      flex-direction: row;
    }
  </style>

</head>

<body>
  <div id="wrap">

  </div>

  <script>

    var Application = function () {
      var sessions = [];
      function c() {
        var n = $('.c').attr('id');
        var c = n;
        $('.c').text(c);
        setInterval(function () {
          c--;
          if (c >= 0) {
            $('.c').text(c);
          }
        }, 1000);
      }

      function consume(message) {
        console.log('Received message:', message);
        if (!sessions.includes(message.sessionId)) {
          $('#wrap').append(`
    <div id=${message.sessionId}>
  <h1 class="info"></h1>
  <div class="eventwrap">
  <pre class="log"></pre>
  <img class="qr" />
  <div>
    </div>
          `);
          sessions.push(message.sessionId);
          setInterval(() => {
            var element = document.getElementById(message.sessionId).children[1];
            element.scrollTop = element.scrollHeight;
          }, 1000);
        };

        if (message.sessionId) {
          $(`#${message.sessionId} .info`).html('Session: ' + message.sessionId);
        };
        if (message.namespace === "qr") {
          $(`#${message.sessionId} .qr`)[0].src = message.data
        }
        if (message.namespace === "ready") {
          const link = (message.data || location.href.substring(0, location.href.length - 1)) + "/api-docs/"
          $(`#${message.sessionId} .log`).html(`${$(`#${message.sessionId} .log`).html()} API Explorer: <a href="${link}" target="_blank"   >${link}</a>\n You may need to refresh the page. and wait <span class="c" id="5"></span> seconds. <br><br><br><br>`);
          // Start
          c();
        }
        if (message.data) {
          if (message.namespace !== "sessionDataBase64") $(`#${message.sessionId} .log`).html(`${$(`#${message.sessionId} .log`).html()} ${message.namespace} ${typeof message.data === 'object' ? JSON.stringify(message.data, null, 4) : message.data} <br>`);
        }
      }
      console.log("Application -> window.location.origin", window.location.origin, window.location.href)

      const socketUrl = window.location.origin
      const fallback = `${window.location.origin}${window.location.pathname.split('/').filter(x => !x.includes('.')).join('/')}`;
      const isReverseProxied = window.location.pathname.split('/').includes('api')
      let socket = io(socketUrl, {
        path: isReverseProxied ? `${window.location.pathname.replace(/\/$/, '')}/socket.io` : `/socket.io`
      });

      socket.io.reconnectionAttempts(3)

      socket.io.on("reconnect_attempt", () => {
        console.log("reconnect_attempt");
      });

      socket.io.on("reconnect_failed", () => {
        console.log("reconnect_failed");
        console.log('trying different URL, transferring all event listeners')
        const callbacks = [
          ...Object.entries(socket._callbacks)
        ]
        socket = io(fallback, {
        path: isReverseProxied ? `${window.location.pathname.replace(/\/$/, '')}/socket.io` : `/socket.io`
        });

        callbacks.map(([key, callbacks]) => callbacks.map(cb => socket.on(`${key.replace('$', '')}`, cb)))
      });

      socket.on('connect', function () {
        console.log('Connected to:', socket);
      });

      socket.on('disconnect', (reason) => {
        sessions.map(sessionId => consume({
          sessionId,
          data: `Connection to the launch logs socket is now closed. You can now close this window or go to the api docs ${window.location.href}/api-docs/`,
          namespace: 'SOCKET'
        }));
        socket.close();
      });
      socket.on('message', consume);
      return {
        socket
      };
    };

    $(function () { var app = Application(); });

  </script>

</body>

</html>